package com.hxzy.common.util;

import lombok.extern.log4j.Log4j2;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 * 根据站长网站获取外网IP和地址
 * 使用技术  JSOUP (帮你封装UrlConnection的http请求以及正则表达式匹配器)
 */
@Log4j2
public class ChinazWebUtil {

    /**
     * 获取得外网IP和城市
     * @return [0]=IP，[1]=城市
     */
    public static String[] getIpAndCity(){
        String[] arr=new String[2];
        try {
            String chinaz = "https://ip.chinaz.com/";
            Document document = Jsoup.connect(chinaz).get();

            Elements elements = document.selectXpath("//*[@id=\"leftinfo\"]/div[3]/div[2]/div[2]");
            //再查询<span>
            Elements spanElements = elements.select("span");
            String ip=spanElements.get(0).text();
            Elements emList = spanElements.get(spanElements.size() - 1).select("em");
            String addresss=emList.get(0).text();
            String st=addresss.split(" ")[0];

            arr[0]=ip;
            arr[1]=st;
        }catch(Exception e){
            log.error(e);
            arr[0]="未知";
            arr[1]="未知";
        }
        return arr;
    }
}
